import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { saveEditor } from '../../api/saveEdit';
import store from '../../store';

function initToolbarBootstrapBindings() {
    var fonts = ['Serif', 'Sans', 'Arial', 'Arial Black', 'Courier', 
            'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande', 'Lucida Sans', 'Tahoma', 'Times',
            'Times New Roman', 'Verdana'],
            fontTarget = $('[title=Font]').siblings('.dropdown-menu');
    $.each(fonts, function (idx, fontName) {
        fontTarget.append($('<li><a data-edit="fontName ' + fontName +'" style="font-family:\''+ fontName +'\'">'+fontName + '</a></li>'));
    });
    $('a[title]').tooltip({container:'body'});
        $('.dropdown-menu input').click(function() {return false;})
            .change(function () {$(this).parent('.dropdown-menu').siblings('.dropdown-toggle').dropdown('toggle');})
        .keydown('esc', function () {this.value='';$(this).change();});

    $('[data-role=magic-overlay]').each(function () { 
        var overlay = $(this), target = $(overlay.data('target')); 
        overlay.css('opacity', 0).css('position', 'absolute').offset(target.offset()).width(target.outerWidth()).height(target.outerHeight());
    });
    if ("onwebkitspeechchange"  in document.createElement("input")) {
        var editorOffset = $('#editor').offset();
        $('#voiceBtn').css('position','absolute').offset({top: editorOffset.top, left: editorOffset.left+$('#editor').innerWidth()-35});
    } else {
        $('#voiceBtn').hide();
    }
}

function showErrorAlert (reason, detail) {
    var msg='';
    if (reason==='unsupported-file-type') { msg = "Unsupported format " +detail; }
    else {
        console.log("error uploading file", reason, detail);
    }
    $('<div class="alert"> <button type="button" class="close" data-dismiss="alert">&times;</button>'+ 
    '<strong>File upload error</strong> '+msg+' </div>').prependTo('#alerts');
}


class Edit extends Component{

    componentDidMount(){
        var _that =this;
         $('#edit-panel').wysiwyg({ fileUploadError: showErrorAlert});
         _that.fixEdit();
        initToolbarBootstrapBindings();  
        window.prettyPrint && prettyPrint();
        $(window).resize(function(){
            _that.fixEdit();
        })
    }

    fixEdit(){
        $('#edit').css('width',document.body.clientWidth - 500 + 'px')
    }

    Editor(){
        var { previewList, activePreview } = this.props;
        console.log(previewList)
        saveEditor();
        var _state = [];
        var content = this.refs.edit.innerHTML;

         _state = previewList.map( p => p.secondnav === activePreview ? {...p, content:content} : p);

         store.dispatch({
             type: 'GET_PREVIEW',
             previewList: _state
         });
    }

    checkContain(e){
        var { isContain } = this.props;
        if(!isContain){
            e.stopPropagation();
            store.dispatch({
                type: 'NEW_PREVIEW',
                newPreview: true
            });

            $('#new-preview-input').val('');
            $('.backcover').show();
            $('#new-preview-error').hide();
        }

    }

    render(){
        var { editContain } = this.props;
        return (
            <section id="edit">
                <div className="btn-toolbar" data-role="editor-toolbar" data-target="#editor" id="edit-head">
                    <div  className="btn-group">
                        <a className="btn" id="saveEdit" title="保存" onClick={this.Editor.bind(this)}><i className="icon-save"></i></a>
                    </div>
                    <div className="btn-group">
                        <a className="btn dropdown-toggle" data-toggle="dropdown" title="Font Size"><i className="icon-text-height"></i>&nbsp;<b className="caret"></b></a>
                        <ul className="dropdown-menu">
                        <li><a data-edit="fontSize 5"><font size="5">Huge</font></a></li>
                        <li><a data-edit="fontSize 3"><font size="3">Normal</font></a></li>
                        <li><a data-edit="fontSize 1"><font size="1">Small</font></a></li>
                        </ul>
                    </div>
                    <div className="btn-group">
                        <a className="btn" data-edit="bold" title="Bold (Ctrl/Cmd+B)"><i className="icon-bold"></i></a>
                        <a className="btn" data-edit="italic" title="Italic (Ctrl/Cmd+I)"><i className="icon-italic"></i></a>
                        <a className="btn" data-edit="strikethrough" title="Strikethrough"><i className="icon-strikethrough"></i></a>
                        <a className="btn" data-edit="underline" title="Underline (Ctrl/Cmd+U)"><i className="icon-underline"></i></a>
                    </div>
                    <div className="btn-group">
                        <a className="btn" data-edit="insertunorderedlist" title="Bullet list"><i className="icon-list-ul"></i></a>
                        <a className="btn" data-edit="insertorderedlist" title="Number list"><i className="icon-list-ol"></i></a>
                        <a className="btn" data-edit="outdent" title="Reduce indent (Shift+Tab)"><i className="icon-indent-left"></i></a>
                        <a className="btn" data-edit="indent" title="Indent (Tab)"><i className="icon-indent-right"></i></a>
                    </div>
                    <div className="btn-group">
                        <a className="btn" data-edit="justifyleft" title="Align Left (Ctrl/Cmd+L)"><i className="icon-align-left"></i></a>
                        <a className="btn" data-edit="justifycenter" title="Center (Ctrl/Cmd+E)"><i className="icon-align-center"></i></a>
                        <a className="btn" data-edit="justifyright" title="Align Right (Ctrl/Cmd+R)"><i className="icon-align-right"></i></a>
                        <a className="btn" data-edit="justifyfull" title="Justify (Ctrl/Cmd+J)"><i className="icon-align-justify"></i></a>
                    </div>
                    <div className="btn-group">
                        <a className="btn dropdown-toggle" data-toggle="dropdown" title="Hyperlink"><i className="icon-link"></i></a>
                            <div className="dropdown-menu input-append">
                                <input className="span2" placeholder="URL" type="text" data-edit="createLink"/>
                                <button className="btn" type="button">Add</button>
                        </div>
                        <a className="btn" data-edit="unlink" title="Remove Hyperlink"><i className="icon-cut"></i></a>
                    </div>
                    <div className="btn-group">
                        <a className="btn" title="Insert picture (or just drag & drop)" id="pictureBtn"><i className="icon-picture"></i></a>
                        <input type="file" data-role="magic-overlay" data-target="#pictureBtn" data-edit="insertImage" />
                    </div>
                    <div className="btn-group">
                        <a className="btn" data-edit="undo" title="Undo (Ctrl/Cmd+Z)"><i className="icon-undo"></i></a>
                        <a className="btn" data-edit="redo" title="Redo (Ctrl/Cmd+Y)"><i className="icon-repeat"></i></a>
                    </div>
                    <input type="text" data-edit="inserttext" id="voiceBtn" x-webkit-speech="" />
                </div>
                <div id="edit-panel" ref="edit" dangerouslySetInnerHTML={{__html: editContain}} onClick={this.checkContain.bind(this)}>
                </div>
            </section>
        )
    }
}

const mapStateToProps  = (state) => {
    return {
        editContain: state.editReducer.editContain,
        previewList: state.previewReducer.previewList,
        activePreview: state.previewReducer.activePreview,
        isContain: state.editReducer.isContain
    }
}

const mapDispatchToProps = (dispatch, ownProps) => {
    return {}
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Edit);